package com.example.grpc.server.service;

import proto.com.example.grpc.common.*;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author linht
 * @date 2025/9/10 10:10
 */
@GrpcService
public class MessageGrpcService extends MessageServiceGrpc.MessageServiceImplBase {

    private static final Logger logger = LoggerFactory.getLogger(MessageGrpcService.class);

    @Override
    public void sendMessage(MessageProto.MessageRequest request, StreamObserver<MessageProto.MessageResponse> responseObserver) {
        logger.info("收到消息: {} from {}", request.getContent(), request.getSender());

        MessageProto.MessageResponse response = MessageProto.MessageResponse.newBuilder()
                .setContent("服务端已收到消息: " + request.getContent())
                .setReceiver(request.getSender())
                .setTimestamp(System.currentTimeMillis())
                .setSuccess(true)
                .build();

        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public StreamObserver<MessageProto.MessageRequest> streamMessages(StreamObserver<MessageProto.MessageResponse> responseObserver) {
        return new StreamObserver<MessageProto.MessageRequest>() {
            @Override
            public void onNext(MessageProto.MessageRequest request) {
                logger.info("流式消息: {} from {}", request.getContent(), request.getSender());

                MessageProto.MessageResponse response = MessageProto.MessageResponse.newBuilder()
                        .setContent("流式响应: " + request.getContent())
                        .setReceiver(request.getSender())
                        .setTimestamp(System.currentTimeMillis())
                        .setSuccess(true)
                        .build();

                responseObserver.onNext(response);
            }

            @Override
            public void onError(Throwable t) {
                logger.error("流式消息错误", t);
            }

            @Override
            public void onCompleted() {
                logger.info("流式消息完成");
                responseObserver.onCompleted();
            }
        };
    }
}
